package org.sky.framework.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.core.io.Resource;

public class RedisCacheUtil {
	private static final String attributeName = "name";
	private static final String attributeTimeToLiveSeconds = "timeToLiveSeconds";

	public static Map<String, Long> readCacheXml(Resource configLocation) {
		Map<String, Long> result = new HashMap<String, Long>();
		try {
			String xml = readXml(configLocation);
			Document document = DocumentHelper.parseText(xml);
			Element root = document.getRootElement();
			List<Element> elements = root.elements();
			for (Element child : elements) {
				if (child != null) {
					Attribute nameAtt = child.attribute(attributeName);
					String name = nameAtt.getValue();
					Attribute timeAtt = child.attribute(attributeTimeToLiveSeconds);
					long time = Long.valueOf(timeAtt.getValue());
					result.put(name, time);
				}
			}
		} catch (Exception e) {
			// ignore
		}
		return result;
	}

	private static String readXml(Resource configLocation) throws Exception {
		StringBuilder sb = new StringBuilder();
		InputStream is = null;
		try {
			is = configLocation.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException ex) {
			throw new Exception("Failed to parse EhCache configuration resource", ex);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException ex) {
					// ignore
				}
			}
		}
		return sb.toString();
	}

}
